import { Behavior } from "./behavior"
import { ResourceBehavior } from "./behavior-type"

export function setupResourceMonitor(behavior: Behavior): () => void {
    // 初始资源收集（页面加载阶段）
    window.addEventListener("load", () => {
        collectResources(behavior)
    })

    // 持续监听动态加载的资源
    const intervalId = setInterval(() => {
        collectResources(behavior)
        performance.clearResourceTimings() // 避免重复收集
    }, 5000)

    return () => clearInterval(intervalId)
}

function collectResources(behavior: Behavior): void {
    if (!performance.getEntriesByType) return

    const entries = performance.getEntriesByType("resource") as PerformanceResourceTiming[]
    const filteredEntries = entries.filter(entry => !["fetch", "xmlhttprequest", "beacon"].includes(entry.initiatorType))

    filteredEntries.forEach(entry => {
        const isFailed = isResourceFailed(entry)
        const resourceData: ResourceBehavior = {
            category: "Resource",
            type: "resource",
            time: Date.now(),
            name: entry.name,
            duration: entry.duration,
            initiatorType: entry.initiatorType,
            isCache: isCache(entry),
            status: isFailed ? "error" : "ok"
        }
        behavior.push(resourceData)
    })
}

// 判断资源是否命中缓存
function isCache(entry: PerformanceResourceTiming): boolean {
    return entry.transferSize === 0 || (entry.transferSize !== 0 && entry.encodedBodySize === 0)
}

// 通过 responseStatus 或 duration 判断资源是否失败
function isResourceFailed(entry: PerformanceResourceTiming): boolean {
    // 现代浏览器：直接检查 responseStatus
    if ("responseStatus" in entry) {
        return (entry.responseStatus as number) === 0 || (entry.responseStatus as number) >= 400 // HTTP 4xx/5xx
    }
    // 旧浏览器兜底逻辑：duration为0可能表示失败
    return (entry as PerformanceEntry).duration === 0
}
